package com.dxy.common.utils;

import com.dxy.common.properties.EncryptProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Slf4j
@Component
public class MD5Util {

    private static EncryptProperties encryptProperties;

    @Autowired
    public MD5Util(EncryptProperties encryptProperties) {
        MD5Util.encryptProperties = encryptProperties;
    }

    private static MessageDigest MD5_DIGEST;//MD5加密
    private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();//加密器

    //初始化
    static {
        try {
            MD5_DIGEST = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public static String getEncryptPassword(String password) {
        String saltPassword = "{" + encryptProperties.getSalt() + "}" + password;
        for (int i = 0; i < encryptProperties.getRepeat(); i++) {
            saltPassword = BASE64_ENCODER.encodeToString(MD5_DIGEST.digest(saltPassword.getBytes()));
        }
        return saltPassword;
    }
}
